#!/bin/sh

## hyphop ##

#= make last fat VIM1 VIM2 VIM3 VIM3L

PR=$(dirname $0)
RP=$(realpath $PR)

cd "$PR" || exit 1

. ./build.conf

[ "$BOARDS" ] || BOARDS="$@"
[ "$BOARDS" ] || \
BOARDS="VIM1 VIM2 VIM3 VIM3L Edge"
#BOARDS="VIM1 VIM2 VIM3 VIM3L"

META_ADD=1

#$((4096*300))
# 2400*512 block
#UBOOT_MAX_SIZE=0x12c000

#new
#0x145000
#1331200

#UBOOT_MAX_SIZE=1228800
#UBOOT_MAX_SIZE=1228800
#UBOOT_ENV_OFFSET=$(printf 0x%X $UBOOT_MAX_SIZE)

#UBOOT_ENV_OFFSET=0x140000
UBOOT_ENV_OFFSET=0x145000
#UBOOT_ENV_OFFSET=0x150000

UBOOT_MAX_SIZE=$((UBOOT_ENV_OFFSET))

#UBOOT_ENV_SIZE=0x2000
UBOOT_ENV_SIZE=0x8000
UBOOT_WITH_ENV_SIZE=$((UBOOT_MAX_SIZE+UBOOT_ENV_SIZE))

[ "$DATE" ] || \
DATE=$(date -R)
[ "$TIME" ] || \
TIME=$(date +%s -d"$DATE")

GIT_LINK=https://github.com/khadas/khadas-uboot

GIT_COM_ID_SHORT=$(git rev-parse --short HEAD)
GIT_COM_ID=$(git rev-parse HEAD)
GIT_COM_TAG=$(git show-ref --tags | grep $GIT_COM_ID)
GIT_COM_TAG=${GIT_COM_TAG##*/}


case $GIT_COM_TAG in
    "") GIT_LINK_REL=$GIT_LINK/releases/;;
    *)  GIT_LINK_REL=$GIT_LINK/releases/tag/$GIT_COM_TAG ;;
esac

for BOARD in $BOARDS ; do

    case $BOARD in
	VIM*)
	;;
	*)
	#continue
	;;
    esac

    for TYPE in sd spi; do

    N=u-boot.$TYPE.bin
    UBOOT_FILE_NAME="$BOARD.$N"
    UBOOT="$UBOOT_DIR2/$BOARD.$N"
    [ -s "$UBOOT" ] || continue
    ls -l1 $UBOOT
    #1310720
    #1317620
    UBOOT_VER=$(cat $UBOOT_DIR2/$BOARD.$UBOOT_VERSION)

    # round pad by 64K

    UBOOT_SIZE=$(grep UBOOT_SIZE $UBOOT.meta 2>/dev/null)
    [ "$UBOOT_SIZE" ] && UBOOT_SIZE=${UBOOT_SIZE##* }
    [ "$UBOOT_SIZE" ] || \
    UBOOT_SIZE=$(stat -L -c%s "$UBOOT")

    truncate -s$UBOOT_SIZE "$UBOOT"

    echo "[i] uboot $BOARD size $UBOOT_SIZE => $UBOOT_WITH_ENV_SIZE ENV_OFFSET::$UBOOT_ENV_OFFSET + ENV_SIZE: $UBOOT_ENV_SIZE"

    [ "$UBOOT_SIZE" -gt "$UBOOT_MAX_SIZE" ] && {
	echo "[e] need inc UBOOT_MAX_SIZE and ENV_OFFSET from $UBOOT_MAX_SIZE => $UBOOT_SIZE+"
#	exit 1
    }

    UBOOT_MD5=$(md5sum "$UBOOT")
    UBOOT_MD5=${UBOOT_MD5%% *}

    for CHK_SUM in $(dd if=$UBOOT bs=1M skip=1|md5sum); do break ; done

#    truncate -s$UBOOT_WITH_ENV_SIZE "$UBOOT"
    truncate -s$UBOOT_MAX_SIZE "$UBOOT"

    [ "$META_ADD" ] && {

# USAGE
#tail -n18 VIM2.u-boot.sd.bin

    META="
##UBOOT_META##
FILE: $UBOOT_FILE_NAME
UBOOT_VER: $UBOOT_VER+
UBOOT_SIZE:    $UBOOT_SIZE
ENV_OFFSET:    $UBOOT_MAX_SIZE
ENV_SIZE:      $((UBOOT_ENV_SIZE+0))
SIZE_WITH_ENV: $UBOOT_WITH_ENV_SIZE
MD5: $UBOOT_MD5
CHK_SUM: $CHK_SUM
DATE: $DATE
TIME: $TIME
GIT_COM_ID: $GIT_COM_ID
GIT_COM_TAG: $GIT_COM_TAG
GIT_DOWNLOAD: $GIT_LINK_REL
GIT_PAGE: $GIT_LINK
DOWNLOAD_LAST: https://dl.khadas.com/Firmware/uboot/mainline/
##UBOOT-META##
##UBOOT##END#"

    truncate -s-$((${#META}+1)) "$UBOOT"
    echo "$META" | tail -n+2 > "$UBOOT.meta"
    echo "$META" | tee -a "$UBOOT"
    }

    [ "$TYPE" = "spi" ] || \
    truncate -s$UBOOT_WITH_ENV_SIZE "$UBOOT"

    done
done
